// =================================================================
// File: mkfs.cpp
// Desc: Contains function for creating a new file system
// =================================================================

// =================================================================
// INCLUDES
// =================================================================

#include <stdio.h>
#include <cstring>
#include "Directory.h"
#include "FSManager.h"
#include "Superblock.h"
#include "Inode.h"
#include "config.h"
#include "commands.h"

using namespace std;
// =================================================================
// FUNCTIONS
// =================================================================

// =================================================================
// Name: mkfs
// Desc: Creates a new file system by setting up, the structures that are
//	 critical for the system, such as the super-block and the root directory
// Args: FSManager* fsm - pointer to FSManager object in use
// =================================================================
void mkfs(FSManager *fsm){
    char *b;
    
    Superblock *sb = new Superblock(FS_SIZE,BLOCK_SIZE,NUM_INODES);
    Directory *root_dir = new Directory(0,0);
    
    fsm->SetSB(sb);
    
    // Write a byte to the end of the file system file
    b = new char[1];
    memset(b,0,1);
    fseek(fsm->GetFP(),(FS_SIZE -1),SEEK_SET);
    fwrite(b,1,1,fsm->GetFP());

    for(int i = 0; i < sb->GetNumInodes(); i++){
        sb->AddFreeInode(i);
    }

    for(int i = 0; i < sb->GetNumDataBlocks(); i++){
        sb->AddFreeDataBlock(i);
    }

    fsm->SetSB(sb);

    fsm->WriteSuperblock();

    fsm->SetRootDirectory(root_dir);
    fsm->SetCurrentDirectory(root_dir);

    Inode *node = new Inode();
    node->SetNumLinks(1);
    fsm->WriteInode(node,sb->FreeInodePop());
    fsm->WriteDirectory(root_dir);

    delete node;

}
